/**
 * @name File compression
 * @description
 *  1、Convert files to img objects
 *  2、Obtain file width to height ratio
 *  3、Custom proportional scaling of width and height attributes. Here, I use a fixed width of 800, and the height is proportional scaling
 *  4、canvas Redraw Picture
 *  5、canvas Convert binary object to file object
 * @returns { File } file
 */
export async function imgCompress(file) {
  // Convert files to img objects
  const img = await fileToImg(file)
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    // Obtain file width to height ratio
    const { width: originWidth, height: originHeight } = img
    const scale = +(originWidth / originHeight).toFixed(2)
    const targetWidth = 1000
    const targetHeight = Math.round(1000 / scale)

    canvas.width = targetWidth
    canvas.height = targetHeight
    context.clearRect(0, 0, targetWidth, targetHeight)
    // canvas Redraw Picture
    context.drawImage(img, 0, 0, targetWidth, targetHeight)
    // canvas Convert binary object to file object
    const type = file.type
    canvas.toBlob(function (blob) {
      const f = new File([blob], file.name, {
        type,
        lastModified: file.lastModified
      })
      resolve(f)
    }, type)
  })
}

// Convert files to img objects
export function fileToImg(file) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    const reader = new FileReader()
    reader.onload = function (e) {
      img.src = e.target.result
    }
    reader.onerror = function (e) {
      reject(e)
    }
    reader.readAsDataURL(file)
    img.onload = function () {
      resolve(img)
    }
    img.onerror = function (e) {
      reject(e)
    }
  })
}